<!-- 展示票务信息 -->
<template>
	<view class="colStart">
		<unicloud-db ref="udb" v-slot:default="{data, loading}" :options="options"
			collection="ndp-theater-product, ndp-theater-product-category" 
			field="_id,name,categoryId,theaterName,city,sessionTimes,gradeMoneys,duration,coverImg,createDate,isInvalid,isDeleted" 
			orderby="createDate asc" 
			:where="where">
			<view v-if="loading" class="loading">加载中...</view>
			<view v-else class="list">
				<uni-list v-if="data.length > 0" clickable>
					<uni-list-item :border="false" clickable v-for="(item,index) in data" @click="onJumpDetail(item)"
						:key="index">
						<template v-slot:body>
							<div class="rowStart" style="width: 100%;">
								<image :src="item.coverImg.url" style="width: 100px; height: 135px; border-radius: 8px;"
									mode="aspectFill">
								</image>
								
								<div style="margin-left: 16px; flex:1;" class="colBetween">
									<div>
										<div class="twoLineText" style="font-size: 18px; font-weight: 500; color:#353535">{{item.name}}</div>
										
										<div>
											<div style="font-size: 15px; font-weight: 400; color: #333333; margin-top: 6px; margin-bottom: 6px;">
												{{getTime(item.sessionTimes)}}
											</div>
											
											<div style="font-size: 15px; font-weight: 400; color: #333333; margin-top: 6px; margin-bottom: 6px;"
												class="singleLineText" v-if="item.city.length > 0 && item.theaterName.length > 0">
												{{item.city}}<span style="color: #999999;"> |
												</span>{{item.theaterName}}
											</div>
										</div>
									</div>
									
									<div class="rowBetween">
										<div style="flex: 1; font-size: 15px; font-weight: 500; color:#deb74e;margin-top: 8px;">
											{{item.categoryId.length > 0 ? item.categoryId[0].name : ""}}</div>
										
										<div style="color: #f04e7c; align-self: flex-end; text-align: right;">￥<span
												style="font-size: 22px; font-weight: bold;">{{getMoney(item.gradeMoneys)}}</span>
											<span style="color: #333333; margin-left: 2px;">起</span>
										</div>
									</div>
									
								</div>
							</div>
						</template>
					</uni-list-item>
				</uni-list>
				<view v-else style="width: 100%; line-height: 60px; background-color: white; text-align: center;">暂无数据</view>
			</view>
		</unicloud-db>
	</view>
</template>

<script lang="ts" setup>
	import { computed, onMounted, ref } from "vue"
	import { onLoad, onReachBottom, onPullDownRefresh, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"
	import { useStore } from "vuex"
	import StrUtil from "@/utils/StrUtils.js"

	const store = useStore()
	const udb = ref()
	const options = ref({})
	const where = ref(`isInvalid==false`)

	const getMoney = computed(() => (moneys : any[]) => {
		// console.log("getMoney moneys:", moneys)
		if (!moneys || moneys.length === 0) {
			return '--'
		}
		// return moneys[0]
		// let money = moneys[0] + ''
		// 从moneys中取最小的
		let money = Math.min(...moneys) + ''
		if (money.endsWith(".00")) {
			return money.substring(0, money.length - 3)
		} else {
			return money
		}
	})

	const getTime = computed(() => (_times : any[string]) => {
		// console.log("----------getTime _times:", _times)
		if (!_times || _times.length === 0) {
			// console.log("-------000")
			return ''
		}
		if (_times.length == 1) {
			// console.log("-------111")
			if (!_times[0]) return ''
			// console.log("-------222")
			return _times[0].substring(0, 10).replaceAll('-', '.') + " " + StrUtil.getWeek(_times[0])
		} else {
			// console.log("-------333")
			let start = _times[0]
			let end = _times[_times.length - 1]
			if (!start || !end) return ''
			// console.log("-------444")
			if (start.substring(0, 4) == end.substring(0, 4)) {
				// console.log("-------555")
				return start.substring(0, 10).replaceAll('-', '.') + " - " + end.substring(5, 10).replaceAll('-', '.')
			} else {
				return start.substring(0, 10).replaceAll('-', '.') + " - " + end.substring(0, 10).replaceAll('-', '.')
			}
		}
		// console.log("-------666")
		return ''
	})
	
	onLoad(async (options) => {
		console.log("------list onLoad")
		console.log("接收到的参数:", options)
		
		// 先正常加载列表页面
		await processListPage(options)
		
		// 加载完成后，检查是否需要跳转到welcomeMp
		await processWelcomeMp(options)
	})
	
	const processListPage = async (options) => {
		console.log("processListPage - 正常加载列表页面")
		// 这里可以添加列表页面的特殊处理逻辑
		// 目前列表页面使用unicloud-db自动加载，无需额外处理
	}
	
	const processWelcomeMp = async (options) => {
		console.log("processWelcomeMp")
		
		try {
			if (options.page === "main_page" && options.tab === "MainPage") {
				console.log("检测到分享参数，准备跳转到welcomeMp进行完整处理")
				
				// 延迟跳转，让用户先看到内容
				setTimeout(() => {
					try {
						console.log("开始执行跳转到welcomeMp")
						// 先尝试redirectTo，如果失败再尝试reLaunch
						uni.redirectTo({
							url: "/pages/launch/welcomeMp" + 
							"?page=" + options.page + 
							"&tab=" + options.tab + 
							"&shareUserId=" + options.shareUserId + 
							"&shareOpenId=" + options.shareOpenId,
							success: () => {
								console.log("redirectTo成功")
							},
							fail: (err) => {
								console.log("redirectTo失败，尝试reLaunch:", err)
								// 如果redirectTo失败，尝试reLaunch
								uni.reLaunch({
									url: "/pages/launch/welcomeMp" + 
									"?page=" + options.page + 
									"&tab=" + options.tab + 
									"&shareUserId=" + options.shareUserId + 
									"&shareOpenId=" + options.shareOpenId
								})
							}
						})
					} catch(ex) {
						console.error("跳转welcomeMp失败:", ex)
					}
				}, 500) // 延迟0.5秒，让用户看到内容
			}
		} catch(ex) {
			console.error("跳转welcomeMp失败:", ex)
		}
	}

	onMounted(() => {
		/////// 测试代码，验证分享进来是否有采集到参数
		// console.warn("ticker/list 有测试代码：验证分享进来是否有采集到参数");
		// let shareData = "";
		// if (!StrUtil.isEmpty(getApp().globalData.shareUserId)) {
		// 	shareData += "分享人userId：" + getApp().globalData.shareUserId;
		// }
		// if (!StrUtil.isEmpty(getApp().globalData.shareOpenId)) {
		// 	shareData += "分享人openId：" + getApp().globalData.shareOpenId;
		// }
		// if (!StrUtil.isEmpty(shareData)) {
		// 	uni.showModal({
		// 		title: "【测试】分享进来的",
		// 		content: shareData,
		// 		showCancel: false,
		// 	});
		// }
		/////// 测试代码，验证分享进来是否有采集到参数
	})

	onReachBottom(() => {
		try {
			if (!StrUtil.isEmpty(udb.value)) {
				udb.value.loadMore()
			}
		} catch (ex) {
			console.error(ex)
		}
	})

	onPullDownRefresh(() => {
		try {
			// setTimeout(() => {
			if (!StrUtil.isEmpty(udb.value)) {
				// udb.value.refresh()
				// uni.stopPullDownRefresh()
				udb.value.loadData({ clear: true }, () => {
					uni.stopPullDownRefresh()
				})
			}
			// }, 100)
		} catch (err) {
			console.error(err)
		}
	})

	const onJumpDetail = (item) => {
		uni.navigateTo({
			url: "/pages/ticker/detail?id=" + item._id
		})
	}
	
	const onJumpRegist = () => {
		// 注册
		uni.navigateTo({
			url: "/pages/launch/regist"
		});
	}
	
	//分享
	onShareAppMessage((options) => {
		console.log("onShareAppMessage.options:", options);
	
		let share =  {
			title: "向您分享小程序：" + getApp().globalData.appName,
			path: "/pages/launch/welcomeMp" +
				"?page=main_page&tab=MainPage" +  // tab: 首页-MainPage，全友圈-FriendList，活动-ActivityList，通讯录-BusinessCard，我的-My,
				"&shareUserId=" + getApp().globalData.curUserId +
				"&shareOpenId=" + getApp().globalData.curOpenId,
			// imageUrl: detail.value.coverImg.url,
		}
		
		console.log(share.path, "xzzz")
		
		return share
	})
	
	onShareTimeline(() => {
		console.log("onShareTimeline");
	
		let share =  {
			title: "向您分享小程序：" + getApp().globalData.appName,
			path: "/pages/launch/welcomeMp",
			query: "page=main_page&tab=MainPage" +  // tab: 首页-MainPage，全友圈-FriendList，活动-ActivityList，通讯录-BusinessCard，我的-My,
				"&shareUserId=" + getApp().globalData.curUserId +
				"&shareOpenId=" + getApp().globalData.curOpenId,
			// imageUrl: detail.value.coverImg.url,
		}
		
		console.log("list页面朋友圈分享path:", share.path)
		console.log("list页面朋友圈分享query:", share.query)
		return share
	})
</script>

<style scoped>
	.cBoard {
		box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.08);
		border-radius: 6px;
		margin: 10px;
		width: calc(100% - 20px);
		padding-bottom: 15px;
	}

	.container {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;
	}

	.scroll-panel {
		overflow: hidden;
		flex: 1;
		width: 100%;
	}

	.cImage {
		width: 100%;
		height: 189px;
		border-top-left-radius: 15px;
		border-top-right-radius: 15px;
	}

	.cSearchFix {
		background-color: white;
		position: fixed;
		height: 100px;
		left: 0;
		right: 0;
		top: 0;
		z-index: 3;
	}

	.cItem {
		width: 100%;
		background-color: white;
	}

	.cWord {
		z-index: 1;
		color: #353535;
		font-size: 16px;
		font-weight: 500px;
		line-height: 32px;
		align-self: flex-start;
		text-align: left;
	}
</style>